package edu.thu.studio.ormdesigner.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.ui.PlatformUI;

import edu.thu.studio.ormdesigner.Activator;
import edu.thu.studio.ormdesigner.editor.ORMMultiPageEditor;
import edu.thu.studio.ormdesigner.model.ORMModel;
import edu.thu.studio.ormdesigner.model.diagram.Diagram;
import edu.thu.studio.ormdesigner.model.diagram.node.Node;
import edu.thu.studio.ormdesigner.model.orm.TableSet;
import edu.thu.studio.ormdesigner.model.orm.ViewSet;
import edu.thu.studio.ormdesigner.model.orm.table.RefColumn;
import edu.thu.studio.ormdesigner.model.orm.table.Reference;
import edu.thu.studio.ormdesigner.model.orm.table.Table;
import edu.thu.studio.ormdesigner.model.orm.view.View;

public class Utils {
    
    /**
     * 获得一个UUID
     * 
     * @return String UUID
     */
    public static String getUUID() {
        String s = UUID.randomUUID().toString();
        // 去掉“-”符号
        return s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18) + s.substring(19, 23) + s.substring(24);
    }
    
    /**
     * 显示异常
     * 
     * @param e
     *            异常
     */
    public static void showExceptionDialog(Throwable e) {
        IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, e.toString(), e);
        
        log(e);
        
        ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
            Properties.dialog_title_error, Properties.error_plugin_message, status);
    }
    
    /**
     * 显示错误
     * 
     * @param message
     *            错误内容
     */
    public static void showErrorDialog(String message) {
        MessageBox messageBox = new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
            SWT.ICON_ERROR | SWT.OK);
        messageBox.setText(Properties.dialog_title_error);
        messageBox.setMessage(message);
        messageBox.open();
    }
    
    /**
     * 显示提示信息
     * 
     * @param message
     *            提示信息
     */
    public static void showMessageDialog(String message) {
        MessageBox messageBox = new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
            SWT.ICON_INFORMATION | SWT.OK);
        messageBox.setText(Properties.dialog_title_information);
        messageBox.setMessage(message);
        messageBox.open();
    }
    
    /**
     * 确认
     * 
     * @param message
     *            信息
     */
    public static boolean showConfirmDialog(String message) {
        return showConfirmDialog(message, SWT.OK, SWT.CANCEL);
        
    }
    
    public static boolean showConfirmDialog(String message, int ok, int cancel) {
        MessageBox messageBox = new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
            SWT.ICON_INFORMATION | ok | cancel);
        messageBox.setText(Properties.dialog_title_confirm);
        messageBox.setMessage(message);
        int result = messageBox.open();
        
        if (result == ok) {
            return true;
        }
        
        return false;
    }
    
    public static ORMMultiPageEditor getActiveEditor() {
        return (ORMMultiPageEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
            .getActiveEditor();
    }
    
    public static ORMModel getORMModel() {
        return getActiveEditor().getORMModel();
    }
    
    public static TableSet getTableSet() {
        return getORMModel().getTableSet();
    }
    
    public static Table getTable(String id) {
        return getTableSet().get(id);
    }
    
    public static ViewSet getViewSet() {
        return getORMModel().getViewSet();
    }
    
    public static View getView(String id) {
        return getViewSet().get(id);
    }
    
    public static Diagram getDiagram(Node node) {
        ORMModel ormModel = getORMModel();
        Iterator<Diagram> iter = ormModel.getDiagrams().iterator();
        while (iter.hasNext()) {
            Diagram diagram = iter.next();
            if (diagram.getNodes().contains(node)) {
                return diagram;
            }
        }
        return null;
    }
    
    public static List<Node> getRefNodes(Node o) {
        List<Node> nodeList = new ArrayList<Node>();
        for (Diagram diagram : getORMModel().getDiagrams()) {
            Iterator<Node> iter = diagram.getNodes().iterator();
            while (iter.hasNext()) {
                Node node = iter.next();
                if (node.getRefId().equals(o.getRefId())) {
                    nodeList.add(node);
                }
            }
        }
        
        return nodeList;
    }
    
    public static boolean isUniqueCode(Table t) {
        ORMModel ormModel = getORMModel();
        for (Table table : ormModel.getTableSet().getObjectList()) {
            if (table.getCode().equals(t.getCode()) && !(table.getId().equals(t.getId()))) {
                return false;
            }
        }
        for (View view : ormModel.getViewSet().getObjectList()) {
            if (view.getCode().equals(t.getCode())) {
                return false;
            }
        }
        return true;
    }
    
    public static boolean isUniqueCode(View v) {
        ORMModel ormModel = getORMModel();
        for (View view : ormModel.getViewSet().getObjectList()) {
            if (view.getCode().equals(v.getCode()) && !(view.getId().equals(v.getId()))) {
                return false;
            }
        }
        for (Table table : ormModel.getTableSet().getObjectList()) {
            if (table.getCode().equals(v.getCode())) {
                return false;
            }
        }
        return true;
    }
    
    public static boolean isUniqueName(Table t) {
        ORMModel ormModel = getORMModel();
        for (Table table : ormModel.getTableSet().getObjectList()) {
            if (table.getName().equals(t.getName()) && !(table.getId().equals(t.getId()))) {
                return false;
            }
        }
        return true;
    }
    
    public static boolean isUniqueName(View v) {
        ORMModel ormModel = getORMModel();
        for (View view : ormModel.getViewSet().getObjectList()) {
            if (view.getName().equals(v.getName()) && !(view.getId().equals(v.getId()))) {
                return false;
            }
        }
        for (Table table : ormModel.getTableSet().getObjectList()) {
            if (table.getCode().equals(v.getCode())) {
                return false;
            }
        }
        return true;
    }
    
    public static boolean hasReference(String fromId, String toId, Table table, String referenceId) {
        ORMModel ormModel = getORMModel();
        if (ormModel.getTableSet().contains(table)) {
            List<Reference> referenceList = table.getReferences().getObjectList();
            for (Reference _reference : referenceList) {
                List<RefColumn> refColumnList = _reference.getRefColumns().getObjectList();
                for (RefColumn refColumn : refColumnList) {
                    if (refColumn.getFrom().equals(fromId) && refColumn.getTo().equals(toId)
                        && !_reference.getId().equals(referenceId)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    public static void log(Throwable e) {
        e.printStackTrace();
        Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, e.getMessage(), e));
    }
    
    public static String null2blank(String str) {
        if (str == null) {
            return "";
        }
        return str;
    }
    
    /**
     * 为空则返回true
     * 
     * @param str
     * @return
     */
    public static boolean isNull(String str) {
        return null2blank(str).length() > 0 ? false : true;
    }
    
    public static Point getIntersectionPoint(Point s, IFigure figure) {
        
        Rectangle r = figure.getBounds();
        
        int x1 = s.x - r.x;
        int x2 = r.x + r.width - s.x;
        int y1 = s.y - r.y;
        int y2 = r.y + r.height - s.y;
        
        int x = 0;
        int dx = 0;
        if (x1 < x2) {
            x = r.x;
            dx = x1;
            
        } else {
            x = r.x + r.width;
            dx = x2;
        }
        
        int y = 0;
        int dy = 0;
        
        if (y1 < y2) {
            y = r.y;
            dy = y1;
            
        } else {
            y = r.y + r.height;
            dy = y2;
        }
        
        if (dx < dy) {
            y = s.y;
        } else {
            x = s.x;
        }
        
        return new Point(x, y);
    }
    
    public static boolean isAlphabet(String str) {
        char[] ch = str.toCharArray();
        
        for (int i = 0; i < ch.length; i++) {
            if (ch[i] < '0' || 'z' < ch[i]) {
                return false;
            }
            
            if ('9' < ch[i] && ch[i] < 'A') {
                return false;
            }
            
            if ('z' < ch[i] && ch[i] < '_') {
                return false;
            }
            
            if ('_' < ch[i] && ch[i] < 'a') {
                return false;
            }
        }
        
        return true;
    }
    
}
